<?php

namespace app\common\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Order;
use app\admin\model\User;
use app\admin\model\user\Finance;
use app\admin\model\user\Invest;
use app\admin\model\user\Statics;
use app\common\model\Config;
use think\Console;
use think\Db;

final class Kd100
{
//    private static $customer = 'A30BDADA224C6D9555E65626D4617CEE';// 客户授权密钥
//    private static $key = 'MhBwqneW3938';// key值

    private static $customer = '52B5B7208AC35F71C10EB0649603D86C';// 客户授权密钥
    private static $key = 'mlpRMxXh2903';// key值

    public function __construct()
    {

    }

    /**
     * 物流信息
     * @param $code
     * @param $toolid
     * @return mixed
     */
    public function logisticsInfo($code, $toolid, $mobile)
    {
        //参数设置
        $param = [
            'com' => $code,              // 快递公司编码
            'num' => $toolid,      // 快递单号
            'phone' => $mobile,                 // 手机号
            'from' => '',                  // 出发地城市
            'to' > '',                    // 目的地城市
            'resultv2' => '1',             // 开启行政区域解析
            'show' => '0',                 // 返回格式：0：json格式（默认），1：xml，2：html，3：text
            'order' => 'desc'              // 返回结果示例:desc降序（默认）,asc 升序
        ];

        //请求参数
        $post_data = $this->makeParam($param);
        $url = 'https://poll.kuaidi100.com/poll/query.do';    //实时查询地址
        $data = $this->sendRequest($url, $post_data);
//var_dump($data);die;
        if (isset($data['returnCode']) && $data['returnCode'] != '200') {
            return ['code' => 0, 'msg' => $data["message"]];
        }

        return ['code' => 1, 'data' => $data["data"], 'res' => $data];
    }

    public function logisticsInfo_cs($code, $toolid, $mobile)
    {
        //参数设置
        $param = [
            'com' => $code,              // 快递公司编码
            'num' => $toolid,      // 快递单号
            'phone' => $mobile,                 // 手机号
            'from' => '',                  // 出发地城市
            'to' > '',                    // 目的地城市
            'resultv2' => '1',             // 开启行政区域解析
            'show' => '0',                 // 返回格式：0：json格式（默认），1：xml，2：html，3：text
            'order' => 'desc'              // 返回结果示例:desc降序（默认）,asc 升序
        ];

        //请求参数
        $post_data = $this->makeParam($param);
        $url = 'https://poll.kuaidi100.com/poll/query.do';    //实时查询地址
        $data = $this->sendRequest($url, $post_data);
//var_dump($data);die;


        return ['code' => 1, 'data' => $data];
    }

    /**
     * 订阅快递消息
     * @param $code
     * @param $toolid
     * @return array
     */
    public function logisticsSb($code, $toolid, $mobile)
    {
        //参数设置
        $param = array(
            'company' => $code,          //快递公司编码
            'number' => $toolid,    //快递单号
            'from' => '',                     //出发地城市
            'to' => '',                       //目的地城市
            'key' => self::$key,                    //客户授权key
            'parameters' => array(
                'callbackurl' => 'https://app.guoshangufen.com/api/Productlisto/logisticsCallBack',          //回调地址
                'salt' => '',                 //加密串
                'resultv2' => '1',            //行政区域解析
                'autoCom' => '0',             //单号智能识别
                'interCom' => '0',            //开启国际版
                'departureCountry' => '',     //出发国
                'departureCom' => '',         //出发国快递公司编码
                'destinationCountry' => '',   //目的国
                'destinationCom' => '',       //目的国快递公司编码
                'phone' => $mobile                 //手机号
            )
        );

        //请求参数
        $post_data = array();
        $post_data["schema"] = 'json';
        $post_data["param"] = json_encode($param);
        $url = 'http://poll.kuaidi100.com/poll';    //订阅请求地址
        $params = "";
        foreach ($post_data as $k => $v) {
            $params .= "$k=" . urlencode($v) . "&";     //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);

        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = json_decode($result, true);

        if (isset($data['returnCode']) && $data['returnCode'] != '200') {
            if ($data['returnCode'] == 501) {
                $this->makeInfo($toolid);
            }
            return ['code' => 0, 'error_code' => $data['returnCode'], 'msg' => $data["message"]];
        }
        $this->makeInfo($toolid);
        return ['code' => 1, 'msg' => $data["message"]];
    }

    public function makeInfo($toolid)
    {
        $row = Db::name('kd_info')->where('tool', $toolid)->find();
        if (!$row) {
            $idata = [
                'tool' => $toolid,
                'createtime' => time()
            ];
            Db::name('kd_info')->insert($idata);
        }
    }

    /**
     * 生成请求参数
     * @param $param
     * @return array
     */
    private function makeParam($param)
    {
        $post_data = [];
        $post_data['customer'] = self::$customer;
        $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $sign = md5($post_data['param'] . self::$key . $post_data['customer']);
        $post_data['sign'] = strtoupper($sign);

        return $post_data;
    }

    /**
     * 发送请求
     * @param $url
     * @param $post_data
     * @return mixed
     */
    private function sendRequest($url, $post_data)
    {
        // 发送请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $res = curl_exec($ch);
        curl_close($ch);
        //第二个参数为true，表示输出json
        $data = json_decode($res, true);
        return $data;
    }
}